package com.denghq.projectbuilder.common.util;

import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class CollectionUtil {

    public static <T> List<List<T>> splitSet(Set<T> dataList, int limit) {
        return splitList(new ArrayList<>(dataList), limit);
    }

    public static <T> List<List<T>> splitList(List<T> dataList, int limit) {
        List<List<T>> resList = new ArrayList<List<T>>();
        if (CollectionUtils.isEmpty(dataList)) {
            return Lists.newArrayList();
        }
        if (dataList.size() <= limit) {
            resList.add(dataList);
            return resList;
        }
        BigDecimal dataSize = new BigDecimal(dataList.size());
        int count = dataSize.divide(new BigDecimal(limit), RoundingMode.CEILING).toBigInteger().intValue();
        for (int i = 0; i < count; i++) {
            if (i == count - 1) {
                resList.add(dataList.subList(i * limit, dataSize.intValue()));
            } else {
                resList.add(dataList.subList(i * limit, (i + 1) * limit));
            }
        }
        return resList;
    }
}
